package org.linitly;

import org.linitly.util.StringUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author: linxiunan
 * @date: 2021/5/31 14:17
 * @descrption:
 */
public class JavaFileCopy {

    private static final String MAIN_CLASS_NAME_PREFIX = "LinitlyBoot";
    private static final String PROJECT_LOG = "Linitly-boot";

    public static void copyJavaFile(File sourceFile, File destDir, String packageName, String projectName) {
        boolean isMainClass = false;
        String beforeMainClassName = "";
        String fileName = sourceFile.getName();
        String mainClassName = "";
        if (fileName.contains(MAIN_CLASS_NAME_PREFIX)) {
            isMainClass = true;
            beforeMainClassName = fileName.replace(".java", "");
            String mainClassNamePrefix = StringUtil.getMainClassNamePrefix(projectName);
            fileName = fileName.replace(MAIN_CLASS_NAME_PREFIX, mainClassNamePrefix);
            mainClassName = beforeMainClassName.replace(MAIN_CLASS_NAME_PREFIX, mainClassNamePrefix);
        }
        String destFilePath = destDir.getPath() + "/" + fileName;

        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;

        try {
//            bufferedWriter = new BufferedWriter(new FileWriter(destFilePath));
//            bufferedReader = new BufferedReader(new FileReader(sourceFile));
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), StandardCharsets.UTF_8));
            printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFilePath), StandardCharsets.UTF_8)));

            String strLine = "";
            while ((strLine = bufferedReader.readLine()) != null) {
                if (isMainClass && strLine.contains(beforeMainClassName)) {
                    strLine = strLine.replace(beforeMainClassName, mainClassName);
                }
                if (strLine.contains(PROJECT_LOG) || strLine.contains(PROJECT_LOG.toLowerCase())) {
                    strLine = strLine.replace(PROJECT_LOG, projectName);
                    strLine = strLine.replace(PROJECT_LOG.toLowerCase(), projectName);
                }
                strLine = strLine.replace(JavaProjectDeal.DEFAULT_PACKAGE_NAME, packageName);
//                bufferedWriter.write(strLine);
//                bufferedWriter.newLine();
                printWriter.write(strLine);
                printWriter.write("\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) bufferedReader.close();
                if (printWriter != null) printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
